import 'dart:math';

import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:share_fit/app/components/refresh/check_refresh_indicator.dart';
import 'package:share_fit/app/components/stacked_line_indicator.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/models/home/edit_widget_item.dart';
import 'package:share_fit/app/models/home/heart_rate_model.dart';
import 'package:share_fit/app/models/home/menstrual_mode.dart';
import 'package:share_fit/app/models/home/spo2_model.dart';
import 'package:share_fit/app/models/home/workout_model.dart';
import 'package:share_fit/app/controllers/home/exercise_records/model/exercise_type.dart' as workout_type;
import 'package:share_fit/app/tools/date_tool.dart';
import 'package:share_fit/generated/locales.g.dart';
import 'package:share_fit/pub/custom_refresh_indicator/custom_refresh_indicator.dart';

import 'home_logic.dart';

class HomePage extends StatelessWidget {
  HomePage({super.key});

  final logic = Get.put(HomeLogic());
  final state = Get.find<HomeLogic>().state;

  static double borderRadius = 50.r;

  @override
  Widget build(BuildContext context) {
    logic.initMyWidget();

    return Scaffold(
      body: _buildRefreshWidget(context),
    );
  }

  Widget _buildRefreshWidget(BuildContext context) {
    return CheckMarkIndicator(
      onRefresh: () => logic.refreshHomePage(),
      controller: logic.refreshController,
      durations: const RefreshIndicatorDurations(
        timeoutDuration: Duration(seconds: 20),
      ),
      style: const CheckMarkStyle(
        loading: CheckMarkColors(content: Colors.redAccent, background: Colors.transparent),
        completed: CheckMarkColors(content: Colors.greenAccent, background: Colors.transparent),
      ),
      child: _buildContainer(context),
    );
  }

  Widget _buildContainer(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(top: 41.w, left: 41.w, right: 41.w),
      child: ListView(
        children: [
          SizedBox(height: 60.h),
          _createTitleZone(context),
          SizedBox(height: 60.h),
          _createActivitySummaryZone(context),
          SizedBox(height: 30.h),
          _createExerciseRecordZone(context),
          SizedBox(height: 30.h),
          _createWidgetListZone(context),
          SizedBox(height: 150.h),
          _createEditWidgetZone(context),
          SizedBox(height: 190.h),
        ],
      ),
    );
  }

  Widget _createTitleZone(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Image.asset('assets/images/home/ic_launcher.png', width: 200.w, height: 200.w),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(LocaleKeys.home_health_slogan.ts, style: TextStyle(fontSize: 48.sp), overflow: TextOverflow.ellipsis),
            // GestureDetector(
            //   child: const Icon(Icons.refresh, color: Colors.blue),
            //   onTap: () => logic.syncWeatherData(),
            // ),
            GestureDetector(
              child: Image.asset('assets/images/home/weather.png', width: 150.w, height: 150.w),
              onTap: () => logic.goWeatherPage(),
            ),
          ],
        ),
        // Row(
        //   mainAxisAlignment: MainAxisAlignment.end,
        //   children: [
        //     GestureDetector(
        //       child: Image.asset('assets/images/home/weather.png', width: 200.w, height: 200.h),
        //       onTap: () => logic.goWeatherPage(),
        //     ),
        //     SizedBox(width: 30.w),
        //   ],
        // ),
        // Row(
        //   children: [
        //     SizedBox(width: 30.w),
        //     Column(
        //       crossAxisAlignment: CrossAxisAlignment.start,
        //       children: [
        //         Row(
        //           children: [
        //             Text(LocaleKeys.health.ts, style: TextStyle(fontSize: 80.sp)),
        //             Image.asset('assets/images/home/watch.png', width: 81.w, height: 116.h),
        //           ],
        //         ),
        //         Text(LocaleKeys.home_health_slogan.ts, style: TextStyle(fontSize: 40.sp))
        //       ],
        //     ),
        //   ],
        // ),
      ],
    );
  }

  /// 活动记录汇总区
  Widget _createActivitySummaryZone(BuildContext context) {
    return Container(
      constraints: BoxConstraints.expand(height: 550.h),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(borderRadius))),
      child: GetBuilder<HomeLogic>(
        id: 'todaySummary',
        builder: (ctrl) => Flex(
          direction: Axis.horizontal,
          children: [
            Expanded(
              child: Stack(
                alignment: Alignment.center,
                children: [
                  SizedBox(
                    height: 390.w,
                    width: 390.w,
                    child: CircularProgressIndicator(
                      strokeWidth: 45.w,
                      strokeCap: StrokeCap.round,
                      backgroundColor: Colors.blue.withOpacity(0.3),
                      valueColor: const AlwaysStoppedAnimation(Colors.blue),
                      value: ctrl.state.todaySummary.getStepProcessValue,
                    ),
                  ),
                  SizedBox(
                    height: 280.w,
                    width: 280.w,
                    child: CircularProgressIndicator(
                      strokeWidth: 45.w,
                      strokeCap: StrokeCap.round,
                      backgroundColor: Colors.amber.withOpacity(0.3),
                      valueColor: const AlwaysStoppedAnimation(Colors.amber),
                      value: ctrl.state.todaySummary.getDistanceProcessValue,
                    ),
                  ),
                  SizedBox(
                    height: 170.w,
                    width: 170.w,
                    child: CircularProgressIndicator(
                      strokeWidth: 45.w,
                      strokeCap: StrokeCap.round,
                      backgroundColor: Colors.red.withOpacity(0.3),
                      valueColor: const AlwaysStoppedAnimation(Colors.red),
                      value: ctrl.state.todaySummary.getCalorieProcessValue,
                    ),
                  ),
                ],
              ),
            ),
            Expanded(
              child: Padding(
                padding: EdgeInsets.only(left: 40.w, right: 30.w, top: 30.w, bottom: 70.w),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Expanded(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(LocaleKeys.today_step_sum_text.ts, style: TextStyle(fontSize: 48.sp)),
                          Text(ctrl.state.todaySummary.getStepSumText, style: TextStyle(fontSize: 40.sp)),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: 15.h,
                      child: LinearProgressIndicator(
                        backgroundColor: Colors.blue.withOpacity(0.3),
                        valueColor: const AlwaysStoppedAnimation(Colors.blue),
                        value: ctrl.state.todaySummary.getStepProcessValue,
                        borderRadius: BorderRadius.circular(5.r),
                      ),
                    ),
                    Expanded(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(LocaleKeys.today_distance_sum_text.ts, style: TextStyle(fontSize: 48.sp)),
                          Text('${ctrl.state.todaySummary.getDistanceSumText}', style: TextStyle(fontSize: 40.sp)),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: 15.h,
                      child: LinearProgressIndicator(
                        backgroundColor: Colors.amber.withOpacity(0.3),
                        valueColor: const AlwaysStoppedAnimation(Colors.amber),
                        value: ctrl.state.todaySummary.getDistanceProcessValue,
                        borderRadius: BorderRadius.circular(5.r),
                      ),
                    ),
                    Expanded(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(LocaleKeys.today_calorie_sum_text.ts, style: TextStyle(fontSize: 48.sp)),
                          Text('${ctrl.state.todaySummary.getCaloriesSumText}', style: TextStyle(fontSize: 40.sp), overflow: TextOverflow.ellipsis),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: 15.h,
                      child: LinearProgressIndicator(
                        backgroundColor: Colors.red.withOpacity(0.3),
                        valueColor: const AlwaysStoppedAnimation(Colors.red),
                        value: ctrl.state.todaySummary.getCalorieProcessValue,
                        borderRadius: BorderRadius.circular(5.r),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 运动记录区
  Widget _createExerciseRecordZone(BuildContext context) {
    return GestureDetector(
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 30.h, horizontal: 50.w),
        constraints: BoxConstraints.expand(height: 410.h),
        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(borderRadius))),
        child: GetBuilder<HomeLogic>(
          id: 'today_workout',
          builder: (_) {
            List<WorkoutModel> workouts = _.state.todayWorkout.workouts;
            return workouts.isEmpty || workouts.first.sportsType == null
                ? Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Image(image: const AssetImage('assets/images/home/exercise_record.png'), height: 101.w, width: 101.w),
                          const Icon(Icons.arrow_forward, color: Colors.cyan),
                        ],
                      ),
                      SizedBox(height: 25.h),
                      Text(LocaleKeys.widgets_exercise.ts, style: TextStyle(fontSize: 56.sp)),
                      SizedBox(height: 20.h),
                      Text(LocaleKeys.home_no_exercise_record_tip.ts, style: TextStyle(fontSize: 48.sp))
                    ],
                  )
                : Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Expanded(
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                Image(image: const AssetImage('assets/images/home/exercise_record.png'), height: 101.w, width: 101.w),
                                SizedBox(width: 25.h),
                                Text(LocaleKeys.widgets_exercise.ts, style: TextStyle(fontSize: 56.sp)),
                              ],
                            ),
                            const Icon(Icons.arrow_forward, color: Colors.cyan),
                          ],
                        ),
                      ),
                      SizedBox(height: 15.h),
                      Expanded(
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: [
                            Column(
                              children: [
                                Text(LocaleKeys.exercise_duration_sum_text.ts, style: TextStyle(fontSize: 56.sp)),
                                Text(workouts[0].durationText, style: TextStyle(fontSize: 48.sp)),
                              ],
                            ),
                            if (workout_type.Type.hasDistanceSports(workouts[0].sportsType!))
                              Column(
                                children: [
                                  Text(LocaleKeys.exercise_distance_sum_text.ts, style: TextStyle(fontSize: 56.sp)),
                                  Text(workouts[0].distanceFormat(), style: TextStyle(fontSize: 48.sp)),
                                ],
                              ),
                            Column(
                              children: [
                                Text(LocaleKeys.today_calorie_sum_text.ts, style: TextStyle(fontSize: 56.sp)),
                                Text(workouts[0].caloriesFormat, style: TextStyle(fontSize: 48.sp)),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ],
                  );
          },
        ),
      ),
      onTap: () => logic.goExerciseRecordsPage(),
    );
  }

  /// 自定义组件区
  Widget _createWidgetListZone(BuildContext context) {
    return GetBuilder<HomeLogic>(
      id: 'hasWidgetList',
      builder: (_) {
        return GridView.builder(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          itemCount: _.state.hasList.length,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            mainAxisSpacing: 29.w,
            crossAxisSpacing: 29.w,
            childAspectRatio: 1,
          ),
          itemBuilder: (context, index) {
            return _buildMyWidgetItem(_.state.hasList[index]);
          },
        );
      },
    );
  }

  /// 编辑小组件区
  Widget _createEditWidgetZone(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      child: Column(
        children: [
          Text(LocaleKeys.home_edit_widget.ts, style: TextStyle(fontSize: 54.sp)),
          SizedBox(height: 35.h),
          GestureDetector(
            onTap: () => logic.goEditWidgetPage(context),
            child: Container(
              constraints: BoxConstraints.expand(height: 140.h),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(borderRadius),
              ),
              child: Icon(Icons.add, size: 110.w, color: Colors.grey),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildMyWidgetItem(EditWidgetItem item) {
    return GestureDetector(
      onTap: () => logic.gotoWidgetPage(item),
      child: Container(
        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(60.r))),
        padding: EdgeInsets.symmetric(horizontal: 35.w, vertical: 40.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 组件标题和logo
            Row(children: [
              Image.asset(item.image!, width: 100.w, height: 100.w),
              SizedBox(width: 24.w),
              Expanded(
                child: Text(
                  item.title,
                  style: TextStyle(fontSize: 56.sp),
                  overflow: TextOverflow.ellipsis,
                  softWrap: true,
                  maxLines: 1,
                ),
              )
            ]),
            // 组件指标值
            Container(
              padding: EdgeInsets.only(left: 30.w, top: 40.h),
              alignment: Alignment.topLeft,
              child: GetBuilder<HomeLogic>(
                id: item.type.code,
                builder: (_) => Text(
                  _.buildIndicatorValue(item),
                  style: TextStyle(fontSize: 40.sp),
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ),
            Expanded(child: _buildChartWidget(item)),
            Image.asset('assets/images/home/dotted_line_2.png', fit: BoxFit.fitWidth),
            // 组件底部
            Container(
              margin: EdgeInsets.only(top: 20.w),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(item.type.indicatorMap!['start']!, style: TextStyle(fontSize: 30.sp, color: Colors.grey)),
                  Text(item.type.indicatorMap!['end']!, style: TextStyle(fontSize: 30.sp, color: Colors.grey)),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildChartWidget(EditWidgetItem item) {
    if (item.title == LocaleKeys.widgets_blood_oxygen.ts) {
      return GetBuilder<HomeLogic>(
        id: Type.bloodOxygen.code,
        builder: (_) => Container(
          alignment: Alignment.center,
          padding: EdgeInsets.only(left: 10.w, top: 20.h, bottom: 30.h),
          child: getBarChart(100, getSpO2Datas(state.spo2Avg.oxygenAvgs)),
        ),
      );
    } else if (item.title == LocaleKeys.widgets_heart_rate.ts) {
      return Container(
        alignment: Alignment.center,
        padding: EdgeInsets.only(top: 20.h, bottom: 30.h),
        child: GetBuilder<HomeLogic>(
          id: Type.heartRate.code,
          builder: (_) {
            return getBarChart(100, getHeartRateDatas(state.hrAvg.heartRates));
          },
        ),
      );
    } else if (item.title == LocaleKeys.widgets_sleep.ts) {
      return GetBuilder<HomeLogic>(
        id: item.type.code,
        builder: (_) => Container(
          padding: EdgeInsets.symmetric(horizontal: 10.w),
          child: LayoutBuilder(builder: (context, constraints) {
            double value = _.state.sleepSummary.getProgressValue;
            double fillWidth = constraints.maxWidth >= 0 && constraints.minWidth >= 0 ? value * constraints.maxWidth - 26.w : 0;
            fillWidth = fillWidth > constraints.maxWidth
                ? constraints.maxWidth - 31.w
                : fillWidth <= 0
                    ? 0
                    : fillWidth + 20.w;
            return Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Row(
                  children: [
                    SizedBox(width: fillWidth > constraints.maxWidth - 30.w ? constraints.maxWidth - 30.w : fillWidth),
                    RotatedBox(
                      quarterTurns: 2,
                      child: Image.asset(
                        'assets/images/home/triangle.png',
                        color: const Color.fromRGBO(145, 115, 252, 1.0),
                        width: 30.w,
                        height: 30.w,
                      ),
                    ),
                  ],
                ),
                SizedBox(
                  width: constraints.maxWidth - 30.w,
                  child: LinearProgressIndicator(
                    backgroundColor: Colors.grey[200],
                    valueColor: const AlwaysStoppedAnimation(Color.fromRGBO(145, 115, 252, 1.0)),
                    value: value,
                    borderRadius: BorderRadius.circular(5.r),
                    minHeight: 40.h,
                  ),
                ),
              ],
            );
          }),
        ),
      );
    } else if (item.title == LocaleKeys.widgets_stress.ts) {
      return GetBuilder<HomeLogic>(
        id: item.type.code,
        builder: (_) => Container(
          padding: EdgeInsets.only(top: 30.w),
          alignment: Alignment.center,
          child: LayoutBuilder(builder: (context, constraints) {
            double space = 10.w;
            double width = constraints.maxWidth / 4 - space;
            int level = _.state.stressSummary.level ?? 0;
            double fillWidth = level <= 0 ? 0 : (level - 1) * width + width / 2;
            return Column(
              children: [
                StackedLineIndicator(
                  space: 5.w,
                  borderRadius: BorderRadius.circular(10.r),
                  borderRadiusApplyToAll: true,
                  stackedItems: [
                    StackedLineModel(color: const Color.fromRGBO(19, 208, 255, 1), width: width),
                    StackedLineModel(color: Colors.greenAccent, width: width),
                    StackedLineModel(color: const Color.fromRGBO(181, 124, 255, 1), width: width),
                    StackedLineModel(color: Colors.red.withOpacity(.7), width: width),
                  ],
                ),
                Row(
                  children: [
                    SizedBox(width: fillWidth),
                    Image.asset('assets/images/home/triangle.png', color: Colors.grey, width: 30.w, height: 30.w),
                  ],
                )
              ],
            );
          }),
        ),
      );
    } else if (item.title == LocaleKeys.widgets_cycle_calendar.ts) {
      return GetBuilder<HomeLogic>(
          id: item.type.code,
          builder: (_) {
            return Container(
              padding: EdgeInsets.only(bottom: 30.w),
              alignment: Alignment.center,
              child: Wrap(
                runSpacing: 10.w,
                crossAxisAlignment: WrapCrossAlignment.center,
                children: getMenstrualChart(_.state.menstrualSummary),
              ),
            );
          });
    }

    if (item.title == LocaleKeys.widgets_fatigue.ts) {
      return Container();
    } else {
      return Container();
    }
  }

  List<Widget> getMenstrualChart(MenstrualModel model) {
    if (!model.menstruating) return [];

    DateTime today = DateTool.truncateHMS();
    Map<DateTime, List<MenstrualEvent>>? map = model.getEventMap(today);

    List<Widget> list = [];
    if (map != null && map.isNotEmpty) {
      for (var entry in map.entries) {
        if (entry.key.compareTo(today) == 0) {
          list.addAll([
            Container(
              height: 60.w,
              width: 60.w,
              alignment: Alignment.center,
              decoration: BoxDecoration(color: Color(entry.value[0].color).withOpacity(.3), shape: BoxShape.circle),
              child: Text(today.day.toString(), style: TextStyle(fontSize: 30.sp, color: Colors.black.withOpacity(.5))),
            ),
            Container(
              height: 5.w,
              width: 30.w,
              decoration: BoxDecoration(
                color: Color(entry.value[0].color),
                shape: BoxShape.rectangle,
                borderRadius: BorderRadius.circular(5.r),
              ),
            ),
          ]);
        } else {
          list.addAll([
            Container(
              height: 40.w,
              width: 40.w,
              alignment: Alignment.center,
              decoration: BoxDecoration(color: Color(entry.value[0].color).withOpacity(.5), shape: BoxShape.circle),
            ),
            Container(
              height: 5.w,
              width: 30.w,
              decoration: BoxDecoration(
                color: Color(entry.value[0].color).withOpacity(.8),
                shape: BoxShape.rectangle,
                borderRadius: BorderRadius.circular(5.r),
              ),
            ),
          ]);
        }
      }

      list.removeLast();
    }
    return list;
  }

  final pilateColor = const Color(0xFFF0F0F0);
  final quickWorkoutColor = const Color(0xFFFF455D);

  Widget getBarChart(double maxY, List<BarChartGroupData> barGroups) {
    return SizedBox(
      child: AspectRatio(
        aspectRatio: 3.8,
        child: BarChart(
          BarChartData(
            alignment: BarChartAlignment.spaceBetween,
            titlesData: const FlTitlesData(
              leftTitles: AxisTitles(),
              rightTitles: AxisTitles(),
              topTitles: AxisTitles(),
              bottomTitles: AxisTitles(),
            ),
            barTouchData: BarTouchData(enabled: false),
            borderData: FlBorderData(show: false),
            gridData: const FlGridData(show: false),
            barGroups: barGroups,
            maxY: maxY,
          ),
        ),
      ),
    );
  }

  List<BarChartGroupData> getSpO2Datas(List<Spo2Summary> lists) {
    List<BarChartGroupData> items = [];
    for (int i = 0; i < lists.length; i++) {
      items.add(generateGroupData(i, 0, min(100, lists[i].oxygenValue.toDouble())));
    }
    return items;
  }

  List<BarChartGroupData> getHeartRateDatas(List<HRSummary> lists) {
    List<BarChartGroupData> items = [];
    for (int i = 0; i < lists.length; i++) {
      items.add(generateGroupData(i, lists[i].heartRateMin.toDouble() / 5, min(100, lists[i].heartRateMax.toDouble())));
    }
    return items;
  }

  BarChartGroupData generateGroupData(
    int x,
    double fromY,
    double toY,
  ) {
    return BarChartGroupData(
      x: x,
      groupVertically: true,
      barRods: [
        BarChartRodData(
          fromY: 0,
          toY: 100,
          color: pilateColor,
          width: 10.w,
        ),
        BarChartRodData(
          fromY: fromY,
          toY: toY,
          color: quickWorkoutColor,
          width: 10.w,
        ),
      ],
    );
  }

  List<FlSpot> getFlSpotLists(List<int> lists) {
    int maxLength = 20;
    List<FlSpot> items = [];
    int length = lists.length;
    if (length > maxLength) {
      length = length - (length - maxLength);
    }
    for (int i = 0; i < length; i++) {
      items.insert(i, FlSpot(i.toDouble(), lists[i].toDouble()));
    }
    return items;
  }
}
